import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, StatusBar, TouchableOpacity, ImageBackground, Image, ScrollView } from "react-native";
import { Button, Icon, Input } from "@rneui/themed";
import { getValue, setObjectValue } from "@/utils/deviceStorage";
import '@ethersproject/shims'
import { ethers } from "ethers";
import Loading from "@/components/LoadingModal";
import api from "@/request/api";
import { Shadow } from "react-native-shadow-2";
import { CoinTransparentArray } from "@/config/config";
import { AESdecrypt, getFullName, guid } from "@/utils/util";
import moment from "moment";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const AddressManage = (props) => {

    const [coinType, setCoinType] = useState('');
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [selectedWallet, setSelectedWallet] = useState({})
    const [rightTitle, setRightTitle] = useState('Manage');
    const [address, setAddress] = useState('');
    const [walletList, setWalletList] = useState([]);
    const [walletList1, setWalletList1] = useState([]);
    const [checkedList, setCheckedList] = useState([]);

    useEffect(() => {
        let str = getValue('coinType')
        setCoinType(str)
        let obj = getValue('selectedWallet')
        setSelectedWallet(obj)
        let list = getValue('walletList')
        setWalletList(list || [])
        setWalletList1(list || [])
    }, [])

    const handlePressManage = () => {
        setCheckedList([])
        setRightTitle(rightTitle === 'Manage' ? 'Complete' : 'Manage')
    }

    const handleSearch = () => {
        if (address) {
            let arr = []
            walletList.forEach(item => {
                if (item.address.toLowerCase() === address.toLowerCase()) {
                    arr.push(item)
                }
            })
            setWalletList(arr)
        } else {
            setWalletList(walletList1)
        }
    }

    const handlePressItem = (item) => {
        setSelectedWallet(item)
        setObjectValue('selectedWallet', item)
    }

    const handleGenerateNewAddress = () => {
        setLoadingVisible(true)
        setTimeout(async () => {
            const path = "m/44'/60'/0'/0/" + walletList?.length.toString()
            let pwd = getValue('lockPwd')
            let encryptStr = getValue('mnemonicStr')
            let decryptStr = AESdecrypt(pwd.substring(0, 16), pwd.substring(16), encryptStr)
            const wallet = ethers.Wallet.fromMnemonic(decryptStr, path);
            const publickey = wallet.publicKey
            let wallet_name = path
            let result = await api.eth_single_create(publickey, wallet_name)
            let obj = {
                wallet_name,
                coin: coinType.toLowerCase(),
                create_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            if (result && result.wallet_id) {
                obj.wallet_id = result.wallet_id
                obj.address = result.address
                walletList.push(obj)
                setWalletList([...walletList])
                setObjectValue('walletList', [...walletList])
            } else if (result.code === '4207' || result.code == 4207) {
                obj.wallet_id = guid()
                obj.address = wallet.address
                walletList.push(obj)
                setWalletList([...walletList])
                setObjectValue('walletList', [...walletList])
            }
            setLoadingVisible(false)
        }, 100);
    }

    const handleDelete = () => {
        if (checkedList && checkedList.length > 0) {
            let arr = JSON.parse(JSON.stringify(walletList))
            for (let i = 0; i < arr.length; i++) {
                if (checkedList.includes(arr[i].wallet_id)) {
                    arr[i].disable = true
                }
            }
            setWalletList(arr)
            setObjectValue('walletList', arr)
            if (checkedList.includes(selectedWallet.wallet_id)) {
                let obj = {}
                arr.forEach(item => {
                    if (!item.disable) {
                        obj = item
                    }
                })
                setSelectedWallet(obj)
                setObjectValue('selectedWallet', obj)
            }
        }
    }

    const handlePressCheck = (value) => {
        let arr = JSON.parse(JSON.stringify(checkedList))
        if (arr && arr.includes(value)) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === value) {
                    arr.splice(i, 1)
                }
            }
        } else {
            arr.push(value)
        }
        setCheckedList(arr)
    }

    const handlePressAll = () => {
        let arr = []
        for (const item of walletList) {
            arr.push(item.wallet_id)
        }
        setCheckedList(arr)
    }

    const renderItem = (item, isSelected) => {
        return (
            <View>
                <View style={styles.itemTop}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 14 * ratio, marginTop: 12 * ratio }}>
                        <Shadow offset={[2, 2]}
                            distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent' radius={50}>
                            <View style={styles.logoBackContent}>
                                <Image source={CoinTransparentArray[item.coin ? item.coin.toUpperCase() : 'ETH']}
                                    style={{ width: 20 * ratio, height: 20 * ratio }} />
                            </View>
                        </Shadow>
                        <View style={{ marginLeft: 19 * ratio }}>
                            <Text style={{ ...styles.title2, color: isSelected ? '#FFFFFF' : '#707070' }}>
                                {item.coin ? item.coin.toUpperCase() : 'ETH'}
                            </Text>
                            <Text style={{ ...styles.title5, color: isSelected ? '#FFFFFF' : '#707070' }}>
                                {getFullName(item.coin)}</Text>
                        </View>
                    </View>
                    {isSelected && <ImageBackground style={{ width: 45 * ratio, height: 47 * ratio }}
                        source={require('@/assets/imgs/checked.png')} />}
                </View>
                <View style={styles.itemBottom}>
                    <Text ellipsizeMode='middle' numberOfLines={1}
                        style={{ ...styles.title3, width: 136 * ratio, marginLeft: 21 * ratio, color: isSelected ? '#FFFFFF' : '#707070' }}>
                        {item.address}</Text>
                    <Text style={{ ...styles.title3, marginRight: 24 * ratio, color: isSelected ? '#FFFFFF' : '#707070' }}>
                        {item.wallet_name}</Text>
                </View>
            </View>
        )
    }
    return (
        <View style={styles.container}>
            {/* headerContent */}
            <View>
                <StatusBar backgroundColor='#5B6DFD' barStyle='light-content' />
                <View style={styles.titleContent}>
                    <View style={{ flexDirection: 'row', width: width, alignItems: 'center', justifyContent: 'space-between', marginTop: 13 * ratio }}>
                        <View style={{ flex: 2 }}>
                            <Icon type="antdesign" name="left" size={16} color='#FFFFFF' style={{ marginLeft: 15 * ratio }}
                                onPress={() => props.navigation.goBack()} />
                        </View>
                        <View style={{ flex: 6, alignItems: 'center' }}>
                            <Text style={styles.title1}>{coinType} Address Manage</Text>
                        </View>
                        <TouchableOpacity style={{ flex: 2 }} onPress={handlePressManage}>
                            <Text style={styles.title3}>{rightTitle}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
            {/* bodyContent */}
            <View style={{ flex: 1 }}>
                <View style={{ flex: 1, alignItems: 'center' }}>
                    <View style={{ width: 340 * ratio, justifyContent: 'flex-start', flexDirection: 'row' }}>
                        <Input
                            containerStyle={styles.textInput}
                            leftIcon={<Icon type="antdesign" name="search1" size={20} color='#898989' />}
                            onChangeText={text => setAddress(text)}
                            value={address}
                            placeholder={`Enter address to retrieve`}
                            placeholderTextColor='#707070'
                            inputContainerStyle={{ borderBottomWidth: 0, height: 40 * ratio }}
                            inputStyle={{ ...styles.title4, paddingLeft: 8 * ratio }}
                        />
                        {rightTitle === 'Manage' ? <TouchableOpacity onPress={handleSearch}>
                            <Image source={require('@/assets/imgs/filter.png')}
                                style={{ width: 37 * ratio, height: 37 * ratio, marginTop: 15 * ratio, marginLeft: 5 * ratio }} />
                        </TouchableOpacity> : <TouchableOpacity onPress={handlePressAll}
                            style={{ justifyContent: 'center', alignItems: 'center', marginTop: 10 * ratio }}>
                            <Text style={{ ...styles.title3, color: '#000000', marginLeft: 11 * ratio }}>All</Text>
                        </TouchableOpacity>}
                    </View>
                </View>
                <View style={{ flex: 8, marginTop: -15 * ratio }}>
                    <ScrollView style={{ flex: 1 }}>
                        {walletList && walletList.map((item, index) => {
                            const isSelected = item.address === selectedWallet.address
                            if (!item.disable) {
                                return (
                                    <View key={index} style={{ marginTop: 15 * ratio, flexDirection: 'row', alignItems: 'center' }}>
                                        <TouchableOpacity style={rightTitle === 'Complete' ? { marginLeft: -20 * ratio } : { marginLeft: 10 * ratio }}
                                            onPress={() => handlePressItem(item)}>
                                            <Shadow offset={[3, 6]}
                                                distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent'>
                                                {isSelected ?
                                                    <ImageBackground source={require('@/assets/imgs/eth_bgc.png')} style={{
                                                        width: 340 * ratio, height: 85 * ratio
                                                    }}>
                                                        {renderItem(item, isSelected)}
                                                    </ImageBackground>
                                                    :
                                                    <ImageBackground source={require('@/assets/imgs/noshow.png')} style={{
                                                        width: 340 * ratio, height: 85 * ratio
                                                    }}>
                                                        {renderItem(item, isSelected)}
                                                    </ImageBackground>}
                                            </Shadow>
                                        </TouchableOpacity>
                                        {rightTitle === 'Complete' &&
                                            <TouchableOpacity style={styles.circle1} onPress={() => handlePressCheck(item.wallet_id)}>
                                                {checkedList.includes(item.wallet_id) && <View style={styles.circle2}></View>}
                                            </TouchableOpacity>}
                                    </View>
                                )
                            }
                        })}
                    </ScrollView>
                </View>
                <View style={{ flex: 1, justifyContent: 'flex-end' }}>
                    {rightTitle === 'Manage' ?
                        <Button buttonStyle={styles.buttonContent1} onPress={handleGenerateNewAddress}>
                            <Text style={{ ...styles.title3, color: '#F9F9F9' }}>Generate new address</Text>
                        </Button>
                        :
                        <Shadow offset={[3, 6]}
                            distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent'>
                            <TouchableOpacity style={styles.buttonContent2} onPress={handleDelete}>
                                <Text style={{ ...styles.title3, color: '#707070' }}>Delete</Text>
                            </TouchableOpacity>
                        </Shadow>}
                </View>
            </View>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    titleContent: {
        width: width,
        height: 54 * ratio,
        backgroundColor: '#5B6DFD'
    },
    circle1: {
        width: 23 * ratio,
        height: 23 * ratio,
        borderWidth: 1,
        borderColor: '#707070',
        borderRadius: 50,
        marginLeft: 9 * ratio,
        justifyContent: 'center',
        alignItems: 'center'
    },
    circle2: {
        width: 13 * ratio,
        height: 13 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 50
    },
    itemTop: {
        width: '100%',
        height: 47 * ratio,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    logoBackContent: {
        width: 30 * ratio,
        height: 30 * ratio,
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#5662EA'
    },
    itemBottom: {
        width: '100%',
        height: 38 * ratio,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    buttonContent1: {
        width: width,
        height: 56 * ratio,
        backgroundColor: '#5A72EC'
    },
    buttonContent2: {
        width: width,
        height: 56 * ratio,
        backgroundColor: '#FFFFFF',
        justifyContent: 'center',
        alignItems: 'center'
    },
    textInput: {
        width: 299 * ratio,
        height: 40 * ratio,
        borderWidth: 1,
        borderColor: '#CACACA',
        borderRadius: 7,
        marginTop: 12 * ratio
    },
    title1: {
        fontSize: 15,
        fontFamily: 'Microsoft YaHei',
        fontWeight: 'bold',
        color: '#F9F9F9',
        lineHeight: 20
    },
    title2: {
        fontSize: 14,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 19
    },
    title3: {
        fontSize: 13,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 18
    },
    title4: {
        fontSize: 12,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#2A2A2A',
        lineHeight: 15
    },
    title5: {
        fontSize: 10,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 13
    }
})
export default AddressManage